package cn.tedu.hwrabbitmq.rabbit;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static cn.tedu.hwrabbitmq.config.RabbitConfiguration.*;

@Slf4j
@Component
public class Rabbit {
    public void directPublish () throws IOException, TimeoutException {
        Connection connection = getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME+"0", BuiltinExchangeType.DIRECT);
        String message = "消息";
        for (int i = 0; i < 3; i++) {
            channel.queueDeclare(QUEUE_NAME+i,true,false,false,null);
            channel.queueBind(QUEUE_NAME+i,EXCHANGE_NAME+"0",ROUTING_KEY+i);
            channel.basicPublish(EXCHANGE_NAME+"0",ROUTING_KEY+i,null,message.getBytes());
            log.debug(QUEUE_NAME+i,EXCHANGE_NAME+"0",ROUTING_KEY+i);
        }

        channel.close();
        connection.close();
    }
    public void fanoutPublish () throws IOException, TimeoutException {
        Connection connection = getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME+"1", BuiltinExchangeType.FANOUT);
        String message = "消息";
        for (int i = 3; i < 6; i++) {
            channel.queueDeclare(QUEUE_NAME+i,true,false,false,null);
            channel.queueBind(QUEUE_NAME+i,EXCHANGE_NAME+"1",ROUTING_KEY+i);
            log.debug(QUEUE_NAME+i,EXCHANGE_NAME+"1",ROUTING_KEY+i);
        }
        channel.basicPublish(EXCHANGE_NAME+"1",ROUTING_KEY+3,null,message.getBytes());
        channel.basicPublish(EXCHANGE_NAME+"1",ROUTING_KEY+4,null,message.getBytes());
        channel.basicPublish(EXCHANGE_NAME+"1",ROUTING_KEY+5,null,message.getBytes());


        channel.close();
        connection.close();
    }
}
